'use strict';
const crypto = require('crypto');
const axios = require('axios');

// === 关键配置参数 ===
const CONFIG = {
  QUERY_WINDOW: 90000,            // 1.5分钟查询窗口
  PLATFORM_DELAY: 10000,           // 10秒延迟补偿
  MAX_ATTEMPTS: 5,                 // 最大重试次数
  
  DEVICE_CONFIG: {
    productKey: 'k25es2SPWFj',
    deviceName: 'device1',
    properties: [
      { identifier: 'LightLux', type: 'int', range: [0, 4095] },
      { identifier: 'Humidity', type: 'float', range: [0, 100] },
      { identifier: 'soilHumidity', type: 'int', range: [0, 4095], convertToPercent: true },
      { identifier: 'temperature', type: 'float', range: [-40, 80] }
    ]
  }
};

// 密钥配置
const ACCESS_KEY_ID = 'LTAI5tHEAG3GCHuV1gzoSzge';
const ACCESS_KEY_SECRET = 'fv6cpr8EyjVnsUM极速WFLmZYXbcBfgVCq';

// Node.js兼容性处理
if (typeof global.TextDecoder === 'undefined') {
  try {
    const util = require('util');
    global.TextDecoder = util.TextDecoder;
    global.TextEncoder = util.TextEncoder;
  } catch (e) {
    console.warn('TextDecoder/TextEncoder不可用:', e.message);
  }
}

/**
 * 数值转换与验证
 */
const convertAndValidateValue = (rawValue, prop) => {
  try {
    let numValue = rawValue;
    if (typeof rawValue === 'string') {
      numValue = parseFloat(rawValue.replace('%', '').replace('!', ''));
    }
    
    let value = prop.type === 'int' ? parseInt(numValue) : numValue;
    
    if (prop.convertToPercent && prop.identifier === 'soilHumidity') {
      const [min, max] = prop.range;
      value = Math.round((value / (max - min)) * 100);
    }
    
    if (prop.range && (value < prop.range[0] || value > prop.range[1])) {
      console.warn(`数值超出范围: ${prop.identifier}=${value}`);
      return null;
    }
    
    return isNaN(value) ? null : value;
  } catch (error) {
    console.error(`数值转换错误(${prop.identifier}):`, error);
    return null;
  }
};

/**
 * 创建规范化的查询字符串
 */
const createCanonicalizedQueryString = (params) => {
  return Object.keys(params)
    .sort()
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&');
};

/**
 * 阿里云API签名方法
 */
const signAliyunApiRequest = (params, secret) => {
  const canonicalized = createCanonicalizedQueryString(params);
  const stringToSign = `GET&%2F&${encodeURIComponent(canonicalized)}`;
  const signKey = `${secret}&`;
  
  return crypto.createHmac('sha1', signKey)
    .update(stringToSign)
    .digest('base64');
};

// 云函数入口
exports.main = async (event, context) => {
  const startTime = Date.now();
  
  const result = {
    code: 200,
    message: 'success',
    data: {},
    timestamps: {},
    meta: {
      startTime: new Date(startTime).toISOString()
    }
  };

  try {
    console.log(`==== 开始执行云函数 [${new Date().toISOString()}] ====`);
    
    // 时间范围计算
    const beijingOffset = 8 * 3600000; // UTC+8
    const beijingNow = Date.now() + beijingOffset;
    const endTime = beijingNow - CONFIG.PLATFORM_DELAY;
    const startTimeQuery = endTime - CONFIG.QUERY_WINDOW;
    
    console.log('有效的查询时间范围(北京时间):', {
      start: new Date(startTimeQuery).toISOString(),
      end: new Date(endTime).toISOString(),
      duration: `${CONFIG.QUERY_WINDOW/1000}秒`
    });

    // 并行查询所有属性
    const queries = CONFIG.DEVICE_CONFIG.properties.map(async (prop) => {
      try {
        console.log(`查询属性: ${prop.identifier}`);
        
        // 基础请求参数 - 修正公共实例参数为小写字母开头
        const requestParams = {
          Action: 'QueryDevicePropertyData',
          Format: 'JSON',
          Version: '2018-01-20',
          AccessKeyId: ACCESS_KEY_ID,
          Timestamp: new Date().toISOString(),
          SignatureMethod: 'HMAC-SHA1',
          SignatureVersion: '1.0',
          SignatureNonce: Math.random().toString(36).substring(2, 15),
          RegionId: 'cn-shanghai',
          ProductKey: CONFIG.DEVICE_CONFIG.productKey,
          DeviceName: CONFIG.DEVICE_CONFIG.deviceName,
          Identifier: prop.identifier,
          StartTime: startTimeQuery,
          EndTime: endTime,
          Asc: '0',
          PageSize: '3',
          iotInstanceId: 'public'  // 关键修正：小写字母开头
        };
        
        // 计算签名
        const signature = signAliyunApiRequest(requestParams, ACCESS_KEY_SECRET);
        
        // 将签名加入参数
        const signedParams = {
          ...requestParams,
          Signature: signature
        };
        
        // 创建规范化查询字符串
        const canonicalized = createCanonicalizedQueryString(signedParams);
        
        // 构建完整URL
        const url = `https://iot.cn-shanghai.aliyuncs.com/?${canonicalized}`;
        
        console.log(`属性 ${prop.identifier} 请求URL: ${url}`);
        
        // 发送请求
        const response = await axios.get(url, {
          timeout: 10000,
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          }
        });
        
        // 打印响应
        console.log(`属性 ${prop.identifier} API响应:`, JSON.stringify(response.data, null, 2));
        
        // 处理响应
        if (response.data.Success) {
          const records = response.data.Data?.List?.PropertyInfo || [];
          console.log(`属性 ${prop.identifier} 获取记录数: ${records.length}`);
          
          for (let record of records) {
            const value = convertAndValidateValue(record.Value, prop);
            if (value !== null) {
              console.log(`属性 ${prop.identifier} 找到有效值: ${value} (原始值: ${record.Value})`);
              return {
                identifier: prop.identifier,
                value,
                timestamp: record.Time
              };
            }
          }
          
          console.warn(`无有效记录: ${prop.identifier}`);
          return null;
        } else {
          throw new Error(`API响应错误: ${response.data.Message} (Code: ${response.data.Code})`);
        }
      } catch (error) {
        const errorMessage = error.response?.data?.Message || error.message;
        const errorCode = error.response?.data?.Code || 'UNKNOWN_ERROR';
        
        console.error(`查询属性失败(${prop.identifier}): ${errorCode} - ${errorMessage}`);
        console.error('错误详情:', error);
        
        return {
          identifier: prop.identifier,
          error: errorMessage,
          code: errorCode
        };
      }
    });
    
    // 等待所有查询完成
    const results = await Promise.all(queries);
    
    // 处理有效结果
    let validDataCount = 0;
    let errorCount = 0;
    results.forEach(item => {
      if (item && item.value !== null) {
        result.data[item.identifier] = item.value;
        result.timestamps[item.identifier] = item.timestamp;
        validDataCount++;
      } else if (item && item.error) {
        if (!result.errors) result.errors = {};
        result.errors[item.identifier] = item.error;
        errorCount++;
      }
    });
    
    // 设置最终状态 - 修复错误统计
    if (validDataCount === 0) {
      result.code = 503;
      result.error = '未获取到有效数据';
      result.message = `请求失败：${Object.values(result.errors || {}).join('; ')}`;
    } else if (errorCount > 0) {
      result.code = 206;
      result.message = `部分数据缺失：${Object.values(result.errors || {}).join('; ')}`;
    }

  } catch (globalError) {
    console.error('[全局错误]', globalError);
    result.code = 500;
    result.error = `服务器错误: ${globalError.message}`;
    result.details = {
      name: globalError.name,
      code: globalError.code,
      stack: globalError.stack
    };
  }
  
  // 添加执行时间
  result.meta.endTime = new Date().toISOString();
  result.meta.executionTime = `${Date.now() - startTime}ms`;
  
  console.log(`==== 结束执行云函数 (${result.meta.executionTime}) ====`);
  console.log('最终结果:', JSON.stringify({
    code: result.code,
    message: result.message,
    dataCount: Object.keys(result.data).length,
    errors: result.errors ? Object.keys(result.errors).length : 0
  }, null, 2));
  
  return result;
};